<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Distributors;
use App\Model\Normal;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;

class ChargeOptionController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected ChargeDetail $chargeDetail;



    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**套餐列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','keyword','distributor_id','is_autoload','mode','type']);
        $page['info'] = $this->distributors->getInfo($request);
        $data['list'] = $this->chargeOption->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }
            if ($page['distributor_id']) {
                $query->where('distributor_id', $page['distributor_id'])
                ->orWhere('distributor_id', 0);
            } else {
                $query->where('distributor_id', $page['info']['id'])
                ->orWhere('distributor_id', 0);
            }
            if($page['is_autoload'] !== ''){
                $query->where('is_autoload',$page['is_autoload']);
            }
            if($page['type']){
                $query->where('type',$page['type']);
            }
        })->where('is_del',1)->orderBy('sort', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();
        $data['total']= $this->chargeOption->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }
            if($page['distributor_id']){
                $query->where('distributor_id',$page['distributor_id'])
                    ->orWhere('distributor_id', 0);
            }else{
                $query->where('distributor_id',$page['info']['id'])
                    ->orWhere('distributor_id', 0);
            }
            if($page['is_autoload'] !== ''){
                $query->where('is_autoload',$page['is_autoload']);
            }
            if($page['type']){
                $query->where('type',$page['type']);
            }
        })->where('is_del',1)->count();
        foreach($data['list'] as $k => $v){
            if($data['list'][$k]['distributor_id'] > 0 ){
                $data['list'][$k]['distributor_name'] = Distributors::where('id',$v['distributor_id'])->value('name');
            }else{
                $data['list'][$k]['distributor_name'] = '平台默认套餐';
            }
            if($v['type'] == 3){
                $data['list'][$k]['service_children'] = ChargeDetail::where('charge_option_id',$v['id'])
                    ->where('type',ChargeDetail::SERVICE_TYPE)
                    ->orderBy('sort','desc')->get()->toArray();
                $data['list'][$k]['elec_children'] = ChargeDetail::where('charge_option_id',$v['id'])
                    ->where('type',3)
//                ->where('is_del',1)
                    ->orderBy('sort','desc')->get()->toArray();
            }else{
                $data['list'][$k]['power_children'] = ChargeDetail::where('charge_option_id',$v['id'])
                    ->where('type',1)
//                ->where('is_del',1)
                    ->orderBy('sort','desc')->get()->toArray();
                $data['list'][$k]['time_children'] = ChargeDetail::where('charge_option_id',$v['id'])
                    ->where('type',2)
//                ->where('is_del',1)
                    ->orderBy('sort','desc')->get()->toArray();
            }


        }
        return $this->success($data);
    }


    /**创建
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
//        try{
         $info = $this->distributors->getInfo($request);
            $data = $request->post();
            if(isset($data['distributor_name'])){
                unset($data['distributor_name']);
            }
            if(isset($data['power_children'])){
                unset($data['power_children']);
            }
            if(isset($data['elec_children'])){
                unset($data['elec_children']);
            }
            if(isset($data['time_children'])){
                unset($data['time_children']);
            }
            if(isset($data['service_children'])){
                unset($data['service_children']);
            }
            if($info['level'] == 2 || !$data['distributor_id']){
                $data['distributor_id'] = $info['id'];
            }
            if (array_key_exists('id',$data) && $data['id'] > 0) {
                $id = $data['id'];
                unset($data['id']);
                if(array_key_exists('updated_at', $data)){
                    unset($data['updated_at']);
                }
                $this->chargeOption->where('id', $id)->update($data);
            } else {
                ChargeOption::create($data);
            }
            return $this->success();
//        }catch (\Exception $exception){
//            return $this->error($exception->getMessage());
//        }
    }

    /**删除
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        Db::beginTransaction();
        try{
            $id = $request->input('id',0,'int');
            if (!$id) {
                return $this->error(ErrorCode::PARAMS_ERR);
            }
            $charge = $this->chargeOption->where('id',$id)->first();
            if($charge->distributor_id<=0){
                return $this->error(code:1001,msg:'不可删除平台默认套餐');
            }
            $this->chargeOption->where('id',$id)->update(['is_del'=>0]);
            ChargeDetail::where('charge_option_id',$id)->update(['is_del'=>0]);
            Device::where('charge_id',$id)->update(['charge_id'=>0]);
            Db::commit();
        return $this->success();
        }catch (\Exception $e){
            Db::rollBack();
            return $this->error(code:1001,msg:'操作繁忙请稍后重试');
        }
    }


    public function getAll(RequestInterface $request){
        $info = $this->distributors->getInfo($request);
        $data= ChargeOption::where(function ($query) use ($info) {
                if($info['level'] == 2){
                    $query->where('distributor_id', $info['id']);
                }else{
                    $distributors = Distributors::where('parent_id',$info['id'])
                        ->orWhere('id',$info['id'])->pluck('id')->toArray();

                    $query->whereIn('distributor_id', $distributors)->orWhere('distributor_id',0);
                }
        })->get();
        return $this->success($data);
    }


    public function onceCreate(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['id','type','service_type','service_fee','elec',
            'service_children','pre_fee','distributor_id',
            'name','is_autoload','fee','power_children','time_children','elec_children','elec_price']);
        if(!$params['name']){
            return $this->error(code:1002,msg:'套餐名称不能为空');
        }
        Db::beginTransaction();
        try{
            if(isset($params['id'])){
                $charge = $this->chargeOption->where('id',$params['id'])->first();
                $charge->is_autoload = $params['is_autoload'];
                $charge->name = $params['name'];
                $charge->fee = $params['fee'];
                $charge->save();
            }else{
                $save['is_autoload'] = $params['is_autoload'];
                $save['name'] = $params['name'];
                if(!$params['distributor_id']){
                    $save['distributor_id'] = $info['id'];
                }else{
                    $save['distributor_id'] = $params['distributor_id'];
                }

                $save['fee'] = $params['fee'];
                $save['pre_fee'] = $params['pre_fee'];
                if($params['type'] == 3){
                    $save['service_type'] = $params['service_type'];
                    $save['service_fee'] = $params['service_fee'];
                    $save['elec_price'] = $params['elec_price'];
                    $save['elec'] = $params['elec'];
                }else{
                    $params['type'] = 1;
                }
                $save['type'] = $params['type'];
                $option = ChargeOption::create($save);
                $params['id'] = $option->id;
            }
            if($params['type'] == 3 && $params['service_type'] == 2 ){
                if(isset($params['service_children'])){
                    $this->chargeDetail->where('charge_option_id',$params['id'])
                        ->where('type',ChargeDetail::POWER_TYPE)
                        ->update(['is_del'=>0]);
                    if(!is_array($params['service_children'])){
                        $params['service_children'] = json_decode($params['service_children'],true);
                    }
                    foreach($params['service_children'] as $k=>$v){
                        $save = [];
                        $save['fee'] = $v['fee'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        $save['type'] = ChargeDetail::SERVICE_TYPE;
                        ChargeDetail::create($save);
                    }
                }
            }
            if(isset($params['power_children'])){
                $this->chargeDetail->where('charge_option_id',$params['id'])
                    ->where('type',ChargeDetail::POWER_TYPE)
                    ->update(['is_del'=>0]);
                if(!is_array($params['power_children'])){
                    $params['power_children'] = json_decode($params['power_children'],true);
                }
                foreach($params['power_children'] as $k => $v){
                    if(isset($v['minutes']) && isset($v['min_power'])&& isset($v['max_power'])){
                        $save = [];
                        $save['minutes'] = $v['minutes'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        $save['type'] = ChargeDetail::POWER_TYPE;
                        ChargeDetail::create($save);
                    }
                }
            }
            if(isset($params['time_children'])){
                $this->chargeDetail->where('charge_option_id',$params['id'])
                    ->where('type', ChargeDetail::TIME_TYPE)
                    ->update(['is_del'=>0]);
                if(!is_array($params['time_children'])){
                    $params['time_children'] = json_decode($params['time_children'],true);
                }
                foreach($params['time_children'] as $k => $v){
                    if(isset($v['minutes']) && isset($v['fee']) && $v['minutes']){
                        $save = [];
                        $save['minutes'] = $v['minutes'];
                        $save['type'] = ChargeDetail::TIME_TYPE;
                        $save['fee'] = $v['fee'];
                        $save['charge_option_id'] = $params['id'];
                        ChargeDetail::create($save);
                    }
                }
            }
            if(isset($params['elec_children'])){
                $this->chargeDetail->where('charge_option_id',$params['id'])
                    ->where('type', ChargeDetail::ELEC_TYPE)
                    ->update(['is_del'=>0]);
                if(!is_array($params['elec_children'])){
                    $params['elec_children'] = json_decode($params['elec_children'],true);
                }
                foreach($params['elec_children'] as $k => $v){
                    if(isset($v['fee'])){
                        $save = [];
//                        $save['elec'] = $v['elec'];
                        $save['type'] = ChargeDetail::ELEC_TYPE;
                        $save['fee'] = $v['fee'];
//                        $save['elec_price'] = $v['elec_price'];
                        $save['charge_option_id'] = $params['id'];
                        ChargeDetail::create($save);
                    }
                }
            }


            Db::commit();
            return $this->success(['charge_option_id'=>$params['id']]);
        }catch(\Exception $e){
            Db::rollBack();
            return $this->error(code:1003,msg:$e->getMessage());
        }
    }


}
